<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 合作所管理（合作所信息）
 */
class Partner extends CI_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model("partner_model");
        $this->load->model("contact_model");
        $this->load->helper('form');
        $this->load->helper('string');
        $this->load->library('form_validation');
    }
    
    /**
     * 合作所列表
     * @param type $page
     */
    public function index($page = 1)
	{
        $conditions = array(
            'keyword' => trim($this->input->post('keyword')),
        );

        $this->config->load('pagination', true);
        $pagination = $this->config->item('pagination');
        $pagination['base_url'] = site_url('partner/index');
        $pagination['total_rows'] = $this->partner_model->fetch_count($conditions);
        $this->load->library('pagination', $pagination);
        
        $data = array(
            'title' => '合作所资料 - 合作所列表',
            'operations' => array(
                array('label' => '添加合作所', 'uri' => 'partner/create'),
            ),
            'conditions' => $conditions,
            'partners' => $this->partner_model->fetch_array($conditions, $pagination['per_page'], $page),
            'pagelink' => $this->pagination->create_links()
        );

		$this->load->view('header', $data);
        $this->load->view('partner/list', $data);
        $this->load->view('footer');
	}
    
    /**
     * 添加合作所
     */
    public function create() {
        
        $data = array(
            'title' => '合作所资料 - 添加合作所',
            'operations' => array(
                array('label' => '合作所列表', 'uri' => 'partner')
            )
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $contacts = $this->_get_form_contacts();
            $fees = $this->_get_form_fees();
            
            $this->_set_form_validation_rules();
            if ($this->form_validation->run()) {
                /* 插入数据 */
                $this->contact_model->insert_batch($contacts);
                
                $partner = $this->_get_form_partner();
                $partner['contact_ids'] = $this->contact_model->insert_ids();
                $partner['fees'] = serialize($fees); // 序列化存储
                $this->partner_model->insert($partner);
                
                $data['sucess_message'] = '您已成功添加了合作所 ' . $partner['p_name'];
                $data['operations'][] = array('label' => '再次添加合作所', 'uri' => 'partner/create');
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            $contacts = array();
            $fees = array();
        }

        /* 显示添加表单 */
        $data['empty_contact_html'] = $this->_get_empty_contact_html();
        $data['contacts_html'] = $this->_get_contacts_html($contacts);
        $data['empty_fee_html'] = $this->_get_empty_fee_html();
        $data['fees_html'] = $this->_get_fees_html($fees);
        $data['action'] = 'partner/create';
        $data['partner'] = $this->partner_model->new_partner();
        $this->load->view('header', $data);
        $this->load->view('partner/form', $data);
        $this->load->view('footer');
    }
    
    /**
     * 修改合作所
     * @param type $id
     */
    public function update($id) {
        $partner = $this->partner_model->get($id);
        if (empty($partner)) {
            /* 合作所不存在 */
            show_404();
        }

        $data = array(
            'title' => '合作所资料 - 修改合作所 - ' . $partner['p_name'],
            'operations' => array(
                array('label' => '合作所列表', 'uri' => 'partner')
            )
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $contacts = $this->_get_form_contacts();
            $fees = $this->_get_form_fees();

            $this->_set_form_validation_rules($id);
            if ($this->form_validation->run()) {
                /* 验证通过，更新数据 */
                $this->contact_model->insert_batch($contacts);
                
                $partner = $this->_get_form_partner();
                $partner['contact_ids'] = $this->contact_model->insert_ids();
                $partner['fees'] = serialize($fees);
                $this->partner_model->update($id, $partner);
                
                $data['sucess_message'] = '您已成功修改了合作所 ' . $partner['p_name'];
                $data['operations'][] = array('label' => '再次修改合作所', 'uri' => 'partner/update/' . $id);
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            /* 没有提交数据 */
            $contacts = $this->contact_model->fetch_array(array('ids' => $partner['contact_ids']));
            $fees = unserialize($partner['fees']);
        }
        
        /* 显示修改表单 */
        $data['empty_contact_html'] = $this->_get_empty_contact_html();
        $data['contacts_html'] = $this->_get_contacts_html($contacts);
        $data['empty_fee_html'] = $this->_get_empty_fee_html();
        $data['fees_html'] = $this->_get_fees_html($fees);
        $data['action'] = 'partner/update/' . $id;
        $data['partner'] = $partner;
        $this->load->view('header', $data);
        $this->load->view('partner/form', $data);
        $this->load->view('footer');
    }
    
    /**
     * 查看合作所
     * @param type $id
     */
    public function view($id) {
        $partner = $this->partner_model->get($id);
        if (empty($partner)) {
            /* 合作所不存在 */
            show_404();
        }

        $data = array(
            'title' => '合作所资料 - 查看合作所 - ' . $partner['p_name'],
            'operations' => array(
                array('label' => '合作所列表', 'uri' => 'partner')
            )
        );
        
        $contacts = $this->contact_model->fetch_array(array('ids' => $partner['contact_ids']));
        $fees = unserialize($partner['fees']);
        
        /* 显示修改表单 */
        $data['p'] = $partner;
        $data['cts'] = $contacts;
        $data['fees'] = $fees;
        $this->load->view('header', $data);
        $this->load->view('partner/view', $data);
        $this->load->view('footer');
    }
    
    /**
     * 删除合作所
     * @param type $id
     */
    public function remove($id) {
        $partner = $this->partner_model->get($id);
        if (empty($partner)) {
            /* 合作所不存在 */
            show_404();
        }
        
        // TODO 判断能否删除
        
        $data = array(
            'title' => '合作所资料 - 删除合作所 - ' . $partner['p_name'],
            'operations' => array(
                array('label' => '合作所列表', 'uri' => 'partner')
            )
        );
        
        $this->partner_model->delete($id);
                
        $data['sucess_message'] = '您已成功删除了合作所 ' . $partner['p_name'];
        $this->load->view('header', $data);
        $this->load->view('footer');

    }

    /**
     * 取联系信息html
     * @return type
     */
    private function _get_empty_contact_html() {
        return trim_line_break($this->load->view('partner/contact', '', true));
    }
    private function _get_contacts_html($contacts) {
        $html = '';
        foreach ($contacts as $contact) {
            $html .= trim_line_break($this->load->view('partner/contact', array('contact' => $contact), true));
        }

        return $html;
    }
    
    /**
     * 取费用信息html
     * @return type
     */
    private function _get_empty_fee_html() {
        return trim_line_break($this->load->view('partner/fee', '', true));
    }
    private function _get_fees_html($fees) {
        $html = '';
        foreach ($fees as $fee) {
            $html .= trim_line_break($this->load->view('partner/fee', array('fee' => $fee), true));
        }

        return $html;
    }

    /**
     * 从表单取合作所信息
     * @return array
     */
    private function _get_form_partner() {
        $in = $this->input;
        
        return array(
            'p_name' => $in->post('p_name'),
            'p_name_en' => $in->post('p_name_en'),
            'p_addr' => $in->post('p_addr'),
            'p_addr_en' => $in->post('p_addr_en'),
            'p_name_abbr' => $in->post('p_name_abbr'),
            'p_country' => $in->post('p_country'),
            'p_mailing_addr' => $in->post('p_mailing_addr'),
            'p_mailing_addr_en' => $in->post('p_mailing_addr_en'),
            'p_currency' => $in->post('p_currency'),
        );
    }
    
    /**
     * 从表单取联系信息
     * @return array
     */
    private function _get_form_contacts() {
        $in = $this->input;

        if ($in->post('ct_contact') == FALSE) {
            return array();
        }
        
        $ct_contacts    = $in->post('ct_contact');
        $ct_positions   = $in->post('ct_position');
        $ct_telephones  = $in->post('ct_telephone');
        $ct_faxs        = $in->post('ct_fax');
        $ct_qqs         = $in->post('ct_qq');
        $ct_others      = $in->post('ct_other');
        
        $contacts = array();
        $count = count($in->post('ct_contact'));
        for ($i = 0; $i < $count; $i++) {
            $contacts[] = array(
                'ct_contact'    => $ct_contacts[$i],
                'ct_position'   => $ct_positions[$i],
                'ct_telephone'  => $ct_telephones[$i],
                'ct_fax'        => $ct_faxs[$i],
                'ct_qq'         => $ct_qqs[$i],
                'ct_other'      => $ct_others[$i],
            );
        }
        
        return $contacts;
    }
    
    /**
     * 从表单取费用信息
     * @return array
     */
    private function _get_form_fees() {
        $in = $this->input;

        if ($in->post('fee_type') == FALSE) {
            return array();
        }
        
        $fee_type    = $in->post('fee_type');
        $fee_amount  = $in->post('fee_amount');
        
        $fees = array();
        $count = count($in->post('fee_type'));
        for ($i = 0; $i < $count; $i++) {
            $fees[] = array(
                'fee_type'    => $fee_type[$i],
                'fee_amount'  => $fee_amount[$i],
            );
        }
        
        return $fees;
    }

    /**
     * 设置表单验证规则
     */
    private function _set_form_validation_rules($id = 0) {
        $fv = $this->form_validation;
        $fv->set_rules('p_name', '名称（中文）', 'trim|required');
        $fv->set_rules('p_name_en', '', 'trim');
        $fv->set_rules('p_addr', '地址（中文）', 'trim|required');
        $fv->set_rules('p_addr_en', '', 'trim');
        $fv->set_rules('p_name_abbr', '名称缩写', "trim|required|is_unique[partners.p_name_abbr.p_id.$id]");
        $fv->set_rules('p_country', '', 'trim');
        $fv->set_rules('p_mailing_addr', '邮寄地址（中文）', 'trim|required');
        $fv->set_rules('p_mailing_addr_en', '', 'trim');
        $fv->set_rules('p_currency', '', 'trim');
        $fv->set_rules('ct_contact', '', 'callback_contact_check');
    }
    
    /**
     * 自定义的验证函数，必须是public
     * @return boolean
     */
    public function contact_check() {
        if ($this->input->post('ct_contact') == FALSE) {
            $this->form_validation->set_message('contact_check', '联系信息中至少要有一条联系人信息');
            return false;
        } else {
            return true;
        }
    }
}

